package hotel;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Vector;

public class GraficaHotel extends JFrame implements ActionListener, KeyListener {
	private static final long serialVersionUID = 1L;
	static ImageIcon iconav = new ImageIcon("Risorse/v5.png");
	ImageIcon iconap = new ImageIcon("Risorse/puntoint.png");
	ImageIcon iconae = new ImageIcon("Risorse/puntoescl.png");
	static ImageIcon iconax = new ImageIcon("Risorse/x4.png");
	public static Database database;
	private GridBagConstraints c = new GridBagConstraints();
	private JComboBox<String> boxCliente, boxCamera;
	private ResultSet rs = null;
	private Salvataggio gestione;
	public static ArrayList<JButton> b;
	public static MyDefaultTableModel modelClienti;
	public static MyDefaultTableModel modelCamere;
	public JScrollPane scroll1;
	public JScrollPane scroll2;
	public String nomeHotel;
	private int numCamere;
	public static JTable tabellaClienti;
	public static JTable tabellaCamere;
	public JPanel mainPanel, p1, p2, p3, p, pannelloTabella1, pannelloTabella2,
			mainPanelT;
	private JTextField cerca;
	private JMenu comandi, visualizza;
	private JFileChooser scegli;
	private JMenuBar barra;
	private JMenuItem addR, removeR, viewC, viewN, addP, removeP, statistiche,
			iniz;
	private Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
	public int larghezza = d.width;
	public int altezza = d.height;
	private JButton addR1, removeR1, addP1, removeP1, setR, setP, addClienti,
			checkIn, checkOut;
	private JRadioButton cercaCliente, cercaCamera, nonSpecificato,
			disponibile, occupata;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void enableOSXFullscreen(Window window) {
		try {
			Class util = Class.forName("com.apple.eawt.FullScreenUtilities");
			Class params[] = new Class[] { Window.class, Boolean.TYPE };
			Method method = util.getMethod("setWindowCanFullScreen", params);
			method.invoke(util, window, true);
		} catch (ClassNotFoundException e1) {
		} catch (Exception e) {
		}
	}

	public GraficaHotel(Salvataggio nome, Database d) throws SQLException,
			IOException {
		String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
		nomeHotel = nome.getNome();
		numCamere = nome.getNumCamere();
		database = d;
		try {
			UIManager.setLookAndFeel(lookAndFeel);
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		setTitle("Gestore " + nomeHotel);
		Image immagineIc = Toolkit.getDefaultToolkit().getImage(
				"Risorse/HOTEL2.png");
		if (System.getProperty("os.name").equals("Mac OS X")) {
			/*
			 * com.apple.eawt.Application application =
			 * com.apple.eawt.Application.getApplication();
			 * application.setDockIconImage(immagineIc);
			 */
		}
		this.setIconImage(immagineIc);
		gestione = nome;
		enableOSXFullscreen(this);
		if (Toolkit.getDefaultToolkit().isFrameStateSupported(
				JFrame.MAXIMIZED_BOTH))
			setExtendedState(JFrame.MAXIMIZED_BOTH);
		else
			setSize(larghezza, altezza);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		CardLayout l = new CardLayout();

		creaTabellaClienti("SELECT * FROM CLIENTI");
		creaTabellaCamere("SELECT * FROM CAMERE");

		// pannello principale
		mainPanel = new JPanel();
		mainPanel.setLayout(l);
		add(mainPanel);

		// pannello contenitore
		p = new JPanel();
		p.setLayout(new BorderLayout());
		mainPanel.add(p);

		// pannello principale tabelle
		mainPanelT = new JPanel();
		mainPanelT.setLayout(l);
		p.add(mainPanelT, BorderLayout.CENTER);

		// pannello 1 (pannello camere)
		p1 = new JPanel();
		mainPanel.add(p1);
		p1.setBackground(Color.BLACK);
		p1.setPreferredSize(new Dimension(larghezza, altezza));
		b = new ArrayList<JButton>();
		p1.setLayout(new GridBagLayout());
		visualizzaCamere("SELECT numero,stato FROM CAMERE");

		// pannello 5 (tabella clienti)
		scroll1 = new JScrollPane(tabellaClienti);
		JTableHeader header1 = tabellaClienti.getTableHeader();
		header1.setReorderingAllowed(true);
		pannelloTabella1.add(header1, BorderLayout.PAGE_START);
		pannelloTabella1.add(scroll1, BorderLayout.CENTER);
		mainPanelT.add(pannelloTabella1);
		pannelloTabella1.setPreferredSize(new Dimension(larghezza / 6,
				altezza / 6));
		tabellaClienti.setAutoCreateRowSorter(false);
		tabellaClienti.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					try {
						new FinestraCliente((String) target.getValueAt(row, 3))
								.setVisible(true);
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
		});

		// pannello 6 (tabella camere)
		scroll2 = new JScrollPane(tabellaCamere);
		JTableHeader header2 = tabellaCamere.getTableHeader();
		header2.setReorderingAllowed(true);
		pannelloTabella2.add(header2, BorderLayout.PAGE_START);
		pannelloTabella2.add(scroll2, BorderLayout.CENTER);
		mainPanelT.add(pannelloTabella2);
		pannelloTabella2.setPreferredSize(new Dimension(larghezza / 6,
				altezza / 6));
		tabellaCamere.setAutoCreateRowSorter(false);
		tabellaCamere.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tabellaCamere.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					try {
						new FinestraCamera((String) target.getValueAt(row, 0))
								.setVisible(true);
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
		});

		// pannello 2 (bottoni)
		p2 = new JPanel();
		p.add(p2, BorderLayout.EAST);
		p2.setLayout(new GridLayout(20, 1, 0, 3));
		p2.setPreferredSize(new Dimension(larghezza / 6, altezza));

		ButtonGroup bg2 = new ButtonGroup();
		ButtonGroup bg3 = new ButtonGroup();

		// pannello 3 (campo di ricerca)
		p3 = new JPanel();
		boxCliente = new JComboBox<String>();
		boxCliente.addItem("nome");
		boxCliente.addItem("cognome");
		boxCliente.addItem("datadinascita");
		boxCliente.addItem("numerodidocumento");
		boxCliente.addItem("datadiarrivo");
		boxCliente.addActionListener(this);
		boxCamera = new JComboBox<String>();
		boxCamera.addItem("numero");
		boxCamera.addItem("numeroposti");
		boxCamera.setVisible(false);

		nonSpecificato = new JRadioButton("Non specificato", true);
		nonSpecificato.addActionListener(this);
		nonSpecificato.setVisible(false);
		disponibile = new JRadioButton("Disponibile");
		disponibile.addActionListener(this);
		disponibile.setVisible(false);
		occupata = new JRadioButton("Occupata");
		occupata.addActionListener(this);
		occupata.setVisible(false);
		cercaCliente = new JRadioButton("Cerca cliente", true);
		cercaCliente.addActionListener(new MyActionListener(l, mainPanelT));
		cercaCamera = new JRadioButton("Cerca camera");
		cercaCamera.addActionListener(new MyActionListener(l, mainPanelT));

		bg2.add(cercaCliente);
		bg2.add(cercaCamera);
		bg3.add(nonSpecificato);
		bg3.add(disponibile);
		bg3.add(occupata);

		p3.add(cercaCliente);
		p3.add(cercaCamera);
		p3.setLayout(new FlowLayout(FlowLayout.LEADING));
		p.add(p3, BorderLayout.NORTH);

		cerca = new JTextField(20);
		cerca.addKeyListener(this);
		p3.add(cerca);
		p3.add(boxCliente);
		p3.add(boxCamera);
		p3.add(nonSpecificato);
		p3.add(disponibile);
		p3.add(occupata);

		p3.setPreferredSize(new Dimension(larghezza, altezza / 25));

		// barra menu
		barra = new JMenuBar();
		setJMenuBar(barra);
		// menu: comandi
		comandi = new JMenu("Comandi");
		barra.add(comandi);
		// azioni: aggiungi camera
		addR = new JMenuItem("Aggiungi camera");
		comandi.add(addR);
		addR.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
				ActionEvent.ALT_MASK));
		addR.addActionListener(this);
		// azioni: rimuovi camera
		removeR = new JMenuItem("Rimuovi camera");
		comandi.add(removeR);
		removeR.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
				ActionEvent.ALT_MASK));
		removeR.addActionListener(this);
		comandi.addSeparator();
		// azioni: aggiungi cliente
		addP = new JMenuItem("Aggiungi cliente");
		comandi.add(addP);
		addP.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3,
				ActionEvent.ALT_MASK));
		addP.addActionListener(this);
		// azioni: rimuovi cliente
		removeP = new JMenuItem("Rimuovi cliente");
		comandi.add(removeP);
		removeP.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4,
				ActionEvent.ALT_MASK));
		removeP.addActionListener(this);
		// statistiche
		comandi.addSeparator();
		statistiche = new JMenuItem("Mostra Statistiche Clienti");
		statistiche.addActionListener(this);
		comandi.add(statistiche);
		// azioni: elimina tutto
		comandi.addSeparator();
		iniz = new JMenuItem("Inizializza Software");
		iniz.addActionListener(this);
		comandi.add(iniz);

		// menu: visualizza
		visualizza = new JMenu("Visualizza");
		barra.add(visualizza);
		ButtonGroup bg1 = new ButtonGroup();
		// visualizza: visualizzazione normale
		viewN = new JRadioButtonMenuItem("Visualizzazione normale", true);
		visualizza.add(viewN);
		bg1.add(viewN);
		viewN.addActionListener(new MyActionListener(l, mainPanel));
		// visualizza: visualizzazione camere
		viewC = new JRadioButtonMenuItem("Visualizzazione camere");
		visualizza.add(viewC);
		bg1.add(viewC);
		viewC.addActionListener(new MyActionListener(l, mainPanel));

		// Aggiungi camera
		addR1 = new JButton("Aggiungi camera");
		Icon aggCamera=new ImageIcon("Risorse/addRImg1.png");
		addR1.setIcon(aggCamera);
		addR1.addActionListener(this);
		p2.add(addR1);
		// Rimuovi camera
		removeR1 = new JButton("Rimuovi camera");
		Icon rimCamera=new ImageIcon("Risorse/removeRImg2.png");
		removeR1.setIcon(rimCamera);
		p2.add(removeR1);
		removeR1.addActionListener(this);
		// Aggiungi cliente
		addP1 = new JButton("Aggiungi Cliente");
		Icon aggCliente=new ImageIcon("Risorse/addPImg.png");
		addP1.setIcon(aggCliente);
		p2.add(addP1);
		addP1.addActionListener(this);
		// Rimuovi cliente
		removeP1 = new JButton("Rimuovi Cliente");
		Icon rimCliente=new ImageIcon("Risorse/removePImg.png");
		removeP1.setIcon(rimCliente);
		p2.add(removeP1);
		removeP1.addActionListener(this);
		// Modifica camera
		setR = new JButton("Modifica camera");
		Icon modCamera=new ImageIcon("Risorse/setRImg2.png");
		setR.setIcon(modCamera);
		p2.add(setR);
		setR.addActionListener(this);
		// Modifica cliente
		setP = new JButton("Modifica Cliente");
		Icon modCliente=new ImageIcon("Risorse/setPImg2.png");
		setP.setIcon(modCliente);
		p2.add(setP);
		setP.addActionListener(this);
		// Aggiungi clienti da File
		addClienti = new JButton("Aggiungi Clienti da File");
		Icon cartella=new ImageIcon("Risorse/cartella.png");
		addClienti.setIcon(cartella);
		p2.add(addClienti);
		addClienti.addActionListener(this);

		// checkIn
		checkIn = new JButton("Check-In");
		Icon checkInImg=new ImageIcon("Risorse/checkInImg2.png");
		checkIn.setIcon(checkInImg);
		p2.add(checkIn);
		checkIn.addActionListener(this);

		// checkOut
		checkOut = new JButton("Check-Out");
		Icon checkOutImg=new ImageIcon("Risorse/checkOutImg2.png");
		checkOut.setIcon(checkOutImg);
		p2.add(checkOut);
		checkOut.addActionListener(this);

		setColor();

	}

	public String getNomeHotel() {
		return nomeHotel;
	}// getNomeHotel

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == addR) {
			new AggiungiCamera(this);
		} else if (e.getSource() == removeR) {
			int[] rows1 = tabellaCamere.getSelectedRows();
			if (rows1.length < 1) {
				JOptionPane.showMessageDialog(null,
						"Nessuna camera selezionata!", "Attenzione",
						JOptionPane.WARNING_MESSAGE, iconae);
				this.setVisible(true);
			} else if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
					null, "Sicuro di voler continuare?", "Avviso",
					JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
					iconap)) {
				mergeSort(rows1, 0, rows1.length - 1);
				for (int i = 0; i < rows1.length; i++) {
					if (database.rimuoviCamera((String) modelCamere.getValueAt(
							rows1[i], 0))) {
						modelCamere.removeRow(rows1[i]);
					}
				}
				this.setVisible(true);
			}
		} else if (e.getSource() == addP) {
			try {
				new AggiungiCliente(this);
			} catch (SQLException | IOException e1) {
				e1.printStackTrace();
			}

		} else if (e.getSource() == addP1) {
			try {
				new AggiungiCliente(this);
			} catch (SQLException | IOException e1) {
				e1.printStackTrace();
			}

		} else if (e.getSource() == removeP) {
			int[] rows = tabellaClienti.getSelectedRows();
			if (rows.length < 1) {
				JOptionPane.showMessageDialog(null,
						"Nessun cliente selezionato!", "Attenzione",
						JOptionPane.WARNING_MESSAGE, iconae);
				this.setVisible(true);
			} else if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
					null, "Sicuro di voler continuare?", "Avviso",
					JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
					iconap)) {
				mergeSort(rows, 0, rows.length - 1);
				for (int i = 0; i < rows.length; i++) {
					if (database.rimuoviCliente((String) modelClienti
							.getValueAt(rows[i], 3))) {
						modelClienti.removeRow(rows[i]);
					}
				}
				this.setVisible(true);
			}

		} else if (e.getSource() == removeP1) {
			int[] rows = tabellaClienti.getSelectedRows();
			if (rows.length < 1) {
				JOptionPane.showMessageDialog(null,
						"Nessun cliente selezionato!", "Attenzione",
						JOptionPane.WARNING_MESSAGE, iconae);
				this.setVisible(true);
			} else if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
					null, "Sicuro di voler continuare?", "Avviso",
					JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
					iconap)) {
				mergeSort(rows, 0, rows.length - 1);
				for (int i = 0; i < rows.length; i++) {
					if (database.rimuoviCliente((String) modelClienti
							.getValueAt(rows[i], 3))) {
						modelClienti.removeRow(rows[i]);
					}
				}
				this.setVisible(true);
			}

		} else if (e.getSource() == b) {

		} else if (e.getSource() == iniz) {
			if (JOptionPane
					.showConfirmDialog(
							null,
							"Quest'azione sarà irreversibile ed inizializzerà il software e gli eventuali database presenti! \n "
									+ "                                                 CONTINUARE?",
							"Inizializza", JOptionPane.YES_NO_CANCEL_OPTION,
							JOptionPane.QUESTION_MESSAGE, iconap) == JOptionPane.YES_OPTION) {

				try {
					database.query("drop table ASSOCIAZIONE");
					database.query("drop table CAMERE");
					database.query("drop table CLIENTI");
					File f = new File("Risorse/fileSalvataggio.gtH");
					f.delete();

					JOptionPane.showMessageDialog(null,
							"Software Inizializzato correttamente! \n"
									+ "    L'applicazione verrà chiusa.",
							"Ottimo", JOptionPane.INFORMATION_MESSAGE, iconav);
					System.exit(0);
				} catch (SQLException | IOException e1) {
					e1.printStackTrace();
				}
			} else
				this.setVisible(true);
		} else if (e.getSource() == addClienti) {
			scegli = new JFileChooser();
			scegli.setAcceptAllFileFilterUsed(false);
			FileNameExtensionFilter fn = new FileNameExtensionFilter(
					"File .txt", "txt");
			scegli.addChoosableFileFilter(fn);
			if (scegli.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				if (popolaTabellaDaFile(scegli.getSelectedFile()
						.getAbsolutePath())) {
					try {
						azzeraTabellaClienti();
						ricercaInTabellaClienti("SELECT * FROM CLIENTI");
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
			this.setVisible(true);
		} else if (e.getSource() == statistiche) {
			new FinestraStatistiche();
		} else if (e.getSource() == addR1) {
			new AggiungiCamera(this);
		} else if (e.getSource() == checkIn) {
			int[] rows = tabellaClienti.getSelectedRows();
			if (rows.length > 0)
				new FinestraCheckIn(rows);
			else {
				JOptionPane.showMessageDialog(null,
						"Seleziona almeno un cliente!", "Attenzione",
						JOptionPane.WARNING_MESSAGE, iconae);
				this.setVisible(true);
			}
		} else if (e.getSource() == checkOut) {
			int row = tabellaCamere.getSelectedRow();
			if (row != -1) {
				try {
					rs = database.stat
							.executeQuery("SELECT stato FROM CAMERE where numero='"
									+ modelCamere.getValueAt(row, 0) + "'");
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
				try {
					if (rs.next()) {
						if (rs.getString(1).compareTo("OCCUPATA") == 0) {
							new FinestraCheckOut(row);
						} else
							JOptionPane.showMessageDialog(null,
									"La camera selezionata è vuota!",
									"Attenzione", JOptionPane.WARNING_MESSAGE,
									iconae);
					}
				} catch (HeadlessException | SQLException e1) {
					e1.printStackTrace();
				}

			} else
				JOptionPane.showMessageDialog(null, "Seleziona una camera!",
						"Attenzione", JOptionPane.WARNING_MESSAGE, iconae);
		} else if (e.getSource() == nonSpecificato) {
			String query = "SELECT * FROM camere  WHERE "
					+ (String) boxCamera.getSelectedItem() + " like '"
					+ cerca.getText() + "%'";
			try {
				azzeraTabellaCamere();
				ricercaInTabellaCamere(query);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

		} else if (e.getSource() == disponibile) {
			String query = "SELECT * FROM camere  WHERE "
					+ (String) boxCamera.getSelectedItem() + " like '"
					+ cerca.getText() + "%' && stato='DISPONIBILE'";
			try {
				azzeraTabellaCamere();
				ricercaInTabellaCamere(query);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

		} else if (e.getSource() == occupata) {
			String query = "SELECT * FROM camere  WHERE "
					+ (String) boxCamera.getSelectedItem() + " like '"
					+ cerca.getText() + "%' && stato='OCCUPATA'";
			try {
				azzeraTabellaCamere();
				ricercaInTabellaCamere(query);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

		} else if (e.getSource() == removeR1) {
			int[] rows1 = tabellaCamere.getSelectedRows();
			if (rows1.length < 1) {
				JOptionPane.showMessageDialog(null,
						"Nessuna camera selezionata!", "Attenzione",
						JOptionPane.WARNING_MESSAGE, iconae);
				this.setVisible(true);
			} else if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
					null, "Sicuro di voler continuare?", "Avviso",
					JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
					iconap)) {
				mergeSort(rows1, 0, rows1.length - 1);
				for (int i = 0; i < rows1.length; i++) {
					if (database.rimuoviCamera((String) modelCamere.getValueAt(
							rows1[i], 0))) {
						modelCamere.removeRow(rows1[i]);
					}
				}
				this.setVisible(true);
			}
		}
	}

	public static boolean popolaTabellaDaFile(String path) {
		try {
			Scanner out = new Scanner(new File(path));
			int i = 0;
			while (out.hasNextLine()) {
				Scanner in = new Scanner(out.nextLine());
				in.useDelimiter("#");
				boolean flag = true;
				i++;
				while (flag) {
					String nome = in.next();
					if (nome.equals("end")) {
						JOptionPane.showMessageDialog(null,
								"File letto correttamente!", "Ottimo",
								JOptionPane.INFORMATION_MESSAGE, iconav);
						return true;
					}
					String cognome = in.next();
					String dataDiNascita = in.next();
					String comuneDiNascita = in.next();
					String provinciaN = in.next();
					String residenza = in.next();
					String provinciaR = in.next();
					String documento = in.next();
					String numDoc = in.next();
					String rilasDa = in.next();
					String rilasIl = in.next();
					String oggi = in.next();
					String indirizzo = in.next();
					String query = "INSERT INTO CLIENTI"
							+ "(nome,cognome,datadinascita,comunedinascita,"
							+ "provinciadinascita,residenza,provinciadiresidenza,tipodidocumento,numerodidocumento,"
							+ "rilasciatoda,datadirilascio,datadiarrivo,indirizzo) values('"
							+ nome
							+ "','"
							+ cognome
							+ "','"
							+ dataDiNascita
							+ "','"
							+ comuneDiNascita
							+ "','"
							+ provinciaN
							+ "','"
							+ residenza
							+ "','"
							+ provinciaR
							+ "','"
							+ documento
							+ "','"
							+ numDoc
							+ "','"
							+ rilasDa
							+ "','"
							+ rilasIl
							+ "','"
							+ oggi
							+ "','"
							+ indirizzo + "')";
					if (!aggiungi(query))
						JOptionPane.showMessageDialog(null, "Cliente " + i
								+ " gia' registrato!", "ERRORE",
								JOptionPane.ERROR_MESSAGE, iconax);
					flag = false;
				}
			}
			return true;
		} catch (Exception e) {
			JOptionPane
					.showMessageDialog(
							null,
							"Il File scelto non è corretto! \n             Per maggiori informazioni leggera la guida.");
			return false;
		}
	}

	private void setColor() {
		barra.setBackground(Color.GRAY);
		p2.setBackground(Color.LIGHT_GRAY);
		p3.setBackground(Color.LIGHT_GRAY);
		comandi.setBackground(Color.GRAY);
		visualizza.setBackground(Color.GRAY);
		tabellaClienti.setGridColor(Color.LIGHT_GRAY);
		tabellaCamere.setGridColor(Color.LIGHT_GRAY);
		cercaCliente.setBackground(Color.LIGHT_GRAY);
		cercaCamera.setBackground(Color.LIGHT_GRAY);
		nonSpecificato.setBackground(Color.LIGHT_GRAY);
		disponibile.setBackground(Color.LIGHT_GRAY);
		occupata.setBackground(Color.LIGHT_GRAY);

	}

	private static boolean aggiungi(String line) {
		try {
			return database.query(line);
		} catch (SQLException | IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyPressed(KeyEvent e) {

	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (e.getSource() == cerca) {
			if (cercaCliente.isSelected()) {
				try {
					String query = "SELECT * FROM clienti  WHERE "
							+ (String) boxCliente.getSelectedItem() + " like '"
							+ cerca.getText() + "%'";
					azzeraTabellaClienti();
					ricercaInTabellaClienti(query);
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}// fine if
			else {
				String query = "SELECT * FROM camere  WHERE "
						+ (String) boxCamera.getSelectedItem() + " like '"
						+ cerca.getText() + "%'";
				try {
					azzeraTabellaCamere();
					ricercaInTabellaCamere(query);
				} catch (SQLException e1) {
					e1.printStackTrace();
				}

			}// fine else
		}// fine cerca

	}

	class MyActionListener implements ActionListener {
		CardLayout l;
		JPanel p;

		public MyActionListener(CardLayout l, JPanel p) {
			this.l = l;
			this.p = p;
		}

		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == viewC) {
				l.last(p);
			} else if (e.getSource() == viewN) {
				l.first(p);
			} else if (e.getSource() == cercaCliente) {
				boxCliente.setVisible(true);
				boxCamera.setVisible(false);
				nonSpecificato.setVisible(false);
				disponibile.setVisible(false);
				occupata.setVisible(false);
				l.first(p);
			} else if (e.getSource() == cercaCamera) {
				boxCliente.setVisible(false);
				boxCamera.setVisible(true);
				nonSpecificato.setVisible(true);
				disponibile.setVisible(true);
				occupata.setVisible(true);
				l.last(p);
			}

		}
	}// MyActionListener

	public void creaTabellaClienti(String query) throws SQLException {
		modelClienti = new MyDefaultTableModel();
		rs = database.stat.executeQuery(query);
		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();

		modelClienti.addColumn("Nome");
		modelClienti.addColumn("Cognome");
		modelClienti.addColumn("Data di nascita");
		modelClienti.addColumn("N.Documento");
		modelClienti.addColumn("Data di arrivo");
		Vector<String> row;
		while (rs.next()) {
			row = new Vector<String>(3);
			for (int i = 2; i <= columnCount; i++) {
				if (i == 2 || i == 3 || i == 4 || i == 10 || i == 13)
					row.add(rs.getString(i));
			}
			modelClienti.addRow(row);
		}
		tabellaClienti = new JTable(modelClienti);
		pannelloTabella1 = new JPanel(new BorderLayout());
	}// creaTabella

	public void creaTabellaCamere(String query) throws SQLException {
		modelCamere = new MyDefaultTableModel();
		rs = database.stat.executeQuery(query);
		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();

		modelCamere.addColumn("N° Camera");
		modelCamere.addColumn("N° posti disponibili");
		modelCamere.addColumn("Matrimoniale");
		modelCamere.addColumn("Stato");

		Vector<String> row;
		while (rs.next()) {
			row = new Vector<String>(columnCount);
			for (int i = 2; i <= columnCount; i++) {
				if (i != 4)
					row.add(rs.getString(i));
			}
			modelCamere.addRow(row);

		}
		tabellaCamere = new JTable(modelCamere);
		pannelloTabella2 = new JPanel(new BorderLayout());

	}

	private void visualizzaCamere(String query) throws SQLException {
		rs = database.stat.executeQuery(query);
		int k = 0, i = 0;
		while (rs.next()) {
			b.add(new JButton(rs.getString(1)));
			b.get(i).setPreferredSize(new Dimension(70, 70));
			if (rs.getString(2).compareTo("DISPONIBILE") == 0)
				b.get(i).setBackground(Color.GREEN);
			else if (rs.getString(2).compareTo("OCCUPATA") == 0)
				b.get(i).setBackground(Color.RED);
			b.get(i).setOpaque(true);
			addg(b.get(i), i % 16, k);
			if (i % 16 == 15)
				k++;
			i++;
		}
	}

	public void ricercaInTabellaClienti(String query) throws SQLException {
		rs = database.stat.executeQuery(query);
		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();
		Vector<String> row;
		while (rs.next()) {
			row = new Vector<String>(columnCount);
			for (int i = 2; i <= columnCount; i++) {
				if (i == 2 || i == 3 || i == 4 || i == 10 || i == 13)
					row.add(rs.getString(i));
			}
			modelClienti.addRow(row);
		}
		tabellaClienti.setModel(modelClienti);
	}// ricercaTabellaClienti

	public void ricercaInTabellaCamere(String query) throws SQLException {
		rs = database.stat.executeQuery(query);
		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();
		Vector<String> row;
		while (rs.next()) {
			row = new Vector<String>(columnCount);
			for (int i = 2; i <= columnCount; i++) {
				if (i != 4)
					row.add(rs.getString(i));
			}
			modelCamere.addRow(row);
		}
		tabellaCamere.setModel(modelCamere);
	}// ricercaTabellaCamere

	public void azzeraTabellaClienti() throws SQLException {
		modelClienti.setRowCount(0);
	}// azzeraTabellaClienti

	public void azzeraTabellaCamere() throws SQLException {
		modelCamere.setRowCount(0);
	}// azzeraTabellaCamere

	public void addg(Component comp, int x, int y) {
		c.gridx = x;
		c.gridy = y;
		p1.add(comp, c);
	}

	class MyDefaultTableModel extends DefaultTableModel {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public boolean isCellEditable(int row, int column) {
			return false;
		}
	}

	private void mergeSort(int[] v, int inf, int sup) {
		if (inf < sup) {
			int med = (inf + sup) / 2;
			mergeSort(v, inf, med);
			mergeSort(v, med + 1, sup);
			merge(v, inf, med, sup);
		}
	}

	private void merge(int[] v, int inf, int med, int sup) {
		int[] aux = new int[sup - inf + 1];
		int i = inf, j = med + 1, k = 0;
		while (i <= med && j <= sup)
			if (v[i] > v[j]) {
				aux[k] = v[i];
				i++;
				k++;
			} else {
				aux[k] = v[j];
				j++;
				k++;
			}
		while (i <= med) {
			aux[k] = v[i];
			i++;
			k++;
		}
		while (j <= sup) {
			aux[k] = v[j];
			j++;
			k++;
		}
		for (k = 0; k < aux.length; k++)
			v[inf + k] = aux[k];
	}


}
